<template>
  <div class="layout-padding">
    <div class="layout-padding-auto layout-padding-view">
      <el-row>
        <div class="mb8" style="width: 100%">
          <el-button icon="folder-add" type="primary" class="ml10" @click="formDialogRef.openDialog()"
            v-auth="'task_taskInfo_add'">
            新 增
          </el-button>
          <el-button plain icon="upload-filled" type="primary" class="ml10" @click="excelUploadRef.show()" v-auth="'sys_user_add'">
						导 入
					</el-button>
          <el-button plain :disabled="multiple" icon="Delete" type="primary"
            v-auth="'task_taskInfo_del'" @click="handleDelete(selectObjs)">
            删 除
          </el-button>


					<right-toolbar v-model:showSearch="showSearch" :export="'task_taskInfo_export'"
                @exportExcel="exportExcel" class="ml10 mr20" style="float: right;"
            @queryTable="getDataList">

						<!-- 新增：任务ID输入框 -->
						<el-input v-model="keyword" size="small" placeholder="请输入任务ID" style="width: 150px;" />

						<!-- 新增：查询按钮 -->
						<el-button icon="search" type="primary" class="ml10" @click="localData">查 询</el-button>

					</right-toolbar>
        </div>
      </el-row>
      <el-table :data="state.dataList" v-loading="state.loading" border
        :cell-style="tableStyle.cellStyle" :header-cell-style="tableStyle.headerCellStyle"
				@selection-change="selectionChangHandle"
        @sort-change="sortChangeHandle">
        <el-table-column type="selection" width="40" align="center" />
        <el-table-column  prop="id" label="任务ID"  show-overflow-tooltip/>
          <el-table-column prop="title" label="任务标题"  show-overflow-tooltip/>
          <el-table-column prop="fileType" label="文件类型"  show-overflow-tooltip/>
          <el-table-column prop="execPpk" label="工作路径"  show-overflow-tooltip/>
          <el-table-column prop="processStatus" label="处理状态"  show-overflow-tooltip/>
          <el-table-column prop="province" label="省份"  show-overflow-tooltip/>
					<el-table-column prop="city" label="城市"  show-overflow-tooltip/>
					<el-table-column prop="district" label="区县"  show-overflow-tooltip/>
					<el-table-column prop="message" label="提示信息"  show-overflow-tooltip/>
          <el-table-column prop="startTime" label="任务开始时间"  show-overflow-tooltip/>
          <el-table-column prop="endTime" label="任务结束时间"  show-overflow-tooltip/>
          <el-table-column prop="sourceClient" label="来源客户端"  show-overflow-tooltip/>
          <el-table-column prop="createUser" label="创建用户"  show-overflow-tooltip/>
          <el-table-column prop="cmccId" label="中移差分解算任务id"  show-overflow-tooltip/>
          <el-table-column prop="cmccMileage" label="CMCC里程(公里)"  show-overflow-tooltip/>
          <el-table-column prop="cmccLog" label="CMCC日志"  show-overflow-tooltip/>
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button icon="edit-pen" text type="primary" v-auth="'task_taskInfo_edit'"
              @click="formDialogRef.openDialog(scope.row.id)">编辑</el-button>
            <el-button icon="delete" text type="primary" v-auth="'task_taskInfo_del'" @click="handleDelete([scope.row.id])">删除</el-button>
						<el-button icon="location" text type="primary" v-auth="'task_taskInfo_del'" @click="showTianDiTuMap(scope.row.id)">轨迹</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination @size-change="sizeChangeHandle" @current-change="currentChangeHandle" v-bind="state.pagination" />
    </div>

    <!-- 编辑、新增  -->
    <form-dialog ref="formDialogRef" @refresh="getDataList(false)" />

    <!-- 导入excel (需要在 upms-biz/resources/file 下维护模板) -->
    <upload-excel
			ref="excelUploadRef"
			title="导入"
			url="/task/taskInfo/import"
      temp-url="/admin/sys-file/local/file/taskInfo.xlsx"
			@refreshDataList="getDataList"
		/>
		<!-- 天地图弹窗组件 -->
		<TianDiTuDialog ref="tianDiTuDialogRef" />
  </div>
</template>

<script setup lang="ts" name="systemTask">
import { BasicTableProps, useTable } from "/@/hooks/table";
import { fetchList, delObjs, getGpggaDataByTaskId, getObj } from "/@/api/task/taskInfo";
import { useMessage, useMessageBox } from "/@/hooks/message";
// 在script setup顶部添加
const TianDiTuDialog = defineAsyncComponent(() => import('./TianDiTuDialog.vue'));

// 引入组件
const FormDialog = defineAsyncComponent(() => import('./form.vue'));

// 定义查询字典

// 定义变量内容
const formDialogRef = ref()
const excelUploadRef = ref();
// 搜索变量
const queryRef = ref()
const showSearch = ref(true)
// 多选变量
const selectObjs = ref([]) as any
const multiple = ref(true)

const state: BasicTableProps = reactive<BasicTableProps>({
  queryForm: {},
  pageList: fetchList
})

//  table hook
const {
  getDataList,
  currentChangeHandle,
  sizeChangeHandle,
  sortChangeHandle,
  downBlobFile,
	tableStyle
} = useTable(state)

// 清空搜索条件
const resetQuery = () => {
  // 清空搜索条件
  queryRef.value?.resetFields()
  // 清空多选
  selectObjs.value = []
  getDataList()
}

// 导出excel
const exportExcel = () => {
  downBlobFile('/task/taskInfo/export', Object.assign(state.queryForm, { ids: selectObjs }), 'taskInfo.xlsx')
}

//定于输入框关键字
const keyword = ref('')

const localData =  async () => {
	// 将 keyword 转换为整数并放入 queryForm 的 id 字段
	const id = parseInt(keyword.value, 10);
	const taskId = isNaN(id) ? undefined : id;

	try {
		if (taskId !== undefined && taskId > 0) {
			const res = await getObj({ id: taskId });
			state.dataList = res.data || []; // 将返回数据赋值给表格
		} else {
			getDataList(); // 如果没有输入 id，则恢复为分页查询
		}
	} catch (err) {
		useMessage().error('查询失败，请检查输入或网络');
	}finally {
		keyword.value = '';
	}
}

// 多选事件
const selectionChangHandle = (objs: { id: string }[]) => {
  selectObjs.value = objs.map(({ id }) => id);
  multiple.value = !objs.length;
};

// 删除操作
const handleDelete = async (ids: string[]) => {
  try {
    await useMessageBox().confirm('此操作将永久删除');
  } catch {
    return;
  }

  try {
    await delObjs(ids);
    getDataList();
    useMessage().success('删除成功');
  } catch (err: any) {
    useMessage().error(err.msg);
  }
};
// 在script setup部分添加
const tianDiTuDialogRef = ref()

// 修改showTianDiTuMap方法
const showTianDiTuMap = async (taskId: number) => {
	try {
		const currentRow = state.dataList.find(item => item.id === taskId);

		// 调用API获取轨迹数据
		const response = await getGpggaDataByTaskId(taskId)

		// 检查响应是否成功
		if (response.code !== 0) {
			ElMessage.error(response.msg || '获取轨迹数据失败')
			return
		}

		// 提取并转换轨迹数据
		const trajectoryData = response.data.map(item => {
			const lat = item.latitudeDirection === 'S' ?
				-parseFloat(item.decimalLatitude) :
				parseFloat(item.decimalLatitude);
			const lng = item.longitudeDirection === 'W' ?
				-parseFloat(item.decimalLongitude) :
				parseFloat(item.decimalLongitude);


			return {
				lng,
				lat,
				alt: parseFloat(item.altitude),
				satelliteCount: parseInt(item.satelliteCount,10),
				originalData: {
					latitudeDirection: item.latitudeDirection,
					longitudeDirection: item.longitudeDirection,
				} };
		});

		// 构造地址信息
		const addressInfo = {
			province: currentRow.province,
			city: currentRow.city,
			district: currentRow.district
		};

		// 打开地图弹窗并传入转换后的数据
		tianDiTuDialogRef.value.openDialog(trajectoryData, currentRow.cmccMileage, addressInfo);
	} catch (error) {
		useMessage().error('获取轨迹数据失败: ' + error.message);
	}
};
</script>
